package at.fhj.swd10.eshop.web.upload;

import java.io.*;
import java.util.ResourceBundle;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;

/**
 * @author David
 */
@ManagedBean
@ViewScoped
public class FileUploadBacking implements Serializable {

    public void listener(FileUploadEvent event) throws Exception {
        UploadedFile item = event.getUploadedFile();
        saveInputStreamInDirectory(item.getInputStream(), item.getName());
    }

    private void saveInputStreamInDirectory(InputStream itemInputStream, String filename) throws Exception {
        OutputStream out = createFileOutputStream(filename);

        int read;
        byte[] bytes = new byte[1024];
        while ((read = itemInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        itemInputStream.close();
        out.flush();
        out.close();
    }

    private FileOutputStream createFileOutputStream(String filename) throws Exception {
        ResourceBundle systemProperties = ResourceBundle.getBundle("properties.system");
        String directory = systemProperties.getString("uploadDirectory");

        File f = new File(directory + filename);
        f.setWritable(true);
        return new FileOutputStream(f);
    }
}
